package Timer;

import java.util.PriorityQueue;

public class MyTimer {
    PriorityQueue<MyTimerTask> queue=new PriorityQueue<>();
    final Object object=new Object();//锁对象
    public MyTimer(){
        Thread t=new Thread(()->{
            while(true){
                synchronized (object){
                    try {
                        while(queue.isEmpty()) {
                            object.wait();
                        }
                        MyTimerTask task=queue.peek();
                        if(task.getTime()>System.currentTimeMillis()){
                            object.wait(task.getTime()-System.currentTimeMillis());
                        }else {
                            task.run();
                            queue.poll();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        t.start();
    }
    public void submit(long time,Runnable runnable){
        synchronized (object){
            MyTimerTask task=new MyTimerTask(time+System.currentTimeMillis(),runnable);
            queue.offer(task);
            object.notifyAll(); //唤醒前面因队列为空而阻塞的等待
        }
    }

    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.submit(1000, new Runnable() {
            @Override
            public void run() {
                System.out.println("1秒后执行....");
            }
        });
        myTimer.submit(5000, new Runnable() {
            @Override
            public void run() {
                System.out.println("5秒后执行....");
            }
        });
        myTimer.submit(3000, new Runnable() {
            @Override
            public void run() {
                System.out.println("3秒后执行....");
            }
        });


    }
}

